Module DirCopy

    Public Sub RecursiveCopyFiles( _
    ByVal sourceDir As String, _
    ByVal destDir As String, _
    ByVal fRecursive As Boolean, ByVal overWrite As Boolean)

        Dim i As Integer
        Dim posSep As Integer
        Dim sDir As String
        Dim aDirs() As String
        Dim sFile As String
        Dim aFiles() As String

        ' Add trailing separators to the supplied paths if they don't exist.
        If Not sourceDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
            sourceDir &= System.IO.Path.DirectorySeparatorChar
        End If

        If Not destDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
            destDir &= System.IO.Path.DirectorySeparatorChar
        End If

        ' Recursive switch to continue drilling down into dir structure.
        If fRecursive Then

            ' Get a list of directories from the current parent.
            aDirs = System.IO.Directory.GetDirectories(sourceDir)

            For i = 0 To aDirs.GetUpperBound(0)

                ' Get the position of the last separator in the current path.
                posSep = aDirs(i).LastIndexOf("\")

                ' Get the path of the source directory.
                sDir = aDirs(i).Substring((posSep + 1), aDirs(i).Length - (posSep + 1))

                ' Create the new directory in the destination directory.
                System.IO.Directory.CreateDirectory(destDir + sDir)

                ' Since we are in recursive mode, copy the children also
                RecursiveCopyFiles(aDirs(i), (destDir + sDir), fRecursive, overWrite)
            Next

        End If

        ' Get the files from the current parent.
        aFiles = System.IO.Directory.GetFiles(sourceDir)


        ' Copy all files.
        For i = 0 To aFiles.GetUpperBound(0)

            ' Get the position of the trailing separator.
            posSep = aFiles(i).LastIndexOf("\")

            ' Get the full path of the source file.
            sFile = aFiles(i).Substring((posSep + 1), aFiles(i).Length - (posSep + 1))
            Try


                ' Copy the file.
                System.IO.File.Copy(aFiles(i), destDir + sFile, False)
                'addToConsoleWindow("Copied " & sFile & " to " & destDir)
            Catch ex As Exception
                If overWrite = False Then
                    Throw New Exception(ex.ToString())
                    'addToConsoleWindow("Skipping..." & ex.Message)
                Else
                    System.IO.File.Copy(aFiles(i), destDir + sFile, True)
                    'addToConsoleWindow("Overwriting old " & sFile & " in " & destDir)
                End If

            End Try
        Next i



    End Sub



End Module
